//
//  JNetworkTools.swift
//  JMicroBlog
//
//  Created by Jason on 19/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
import SystemConfiguration
import Alamofire
import SVProgressHUD

// MARK: - 专门负责针对网络请求的操作
class JNetworkTools: NSObject {
    /**
    联网状态的判断
    
    :returns: 是否联网
    */
    class func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
        }
        
        var flags: SCNetworkReachabilityFlags = 0
        if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
            return false
        }
        
        let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        
        return (isReachable && !needsConnection) ? true : false
    }
    
    /**
    网络请求控制器
    
    :param: method     网路请求方式
    :param: URLString  请求地址
    :param: params     请求参数
    :param: completion 回调
    */
    class func responseJSON(method:Alamofire.Method, URLString: String, params: [String: AnyObject]? = nil,completion:(JSON:AnyObject?)->()) {
        Alamofire.request(method, URLString, parameters: params).responseJSON{
            (_,_,JSON,error) in
            
            if error != nil || JSON == nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力!")
                JLog.i("JSON:\(JSON) ERROR:\(error)")
                completion(JSON:nil)
                return
            }
            
            completion(JSON:JSON!)
        }
    }
    
    static let boundary = "JMicroBlog-upload"
    class func uploadPicture(URLString:String,fieldName:String,dataList:[String:NSData!],parameters:[String:AnyObject]? = nil) {
//        var request = NSMutableURLRequest(URL:NSURL(string: URLString)!)
//        request.HTTPMethod = "POST"
//        let type = "multipart/form-data; bounary=\(boundary)"
//        request.setValue(type, forHTTPHeaderField: "Content-type")
//        let data = formData(filedName, dataList: dataList, parameters: parameters)
//        Alamofire.upload(request, data!).responseJSON{ (_,_,JSON,error) in
//            println(error)
//            println(JSON)
//        }
        var request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
        
        // 1. 设置请求的方法
        request.HTTPMethod = "POST"
        // 2. 设置 content-type
        let type = "multipart/form-data; boundary=\(boundary)"
        request.setValue(type, forHTTPHeaderField: "Content-Type")
        
        let data = formData(fieldName, dataList: dataList, parameters: parameters)
        
//        Alamofire.upload(request, data).responseJSON() { (_, _, JSON, error) -> Void in
//            println(error)
//            println(JSON)
//        }
        NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) { (serverData, _, _) in
            // 反序列化
            let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) as! NSDictionary
            JLog.i("\(result)")
        }
    }
    /**
    生成上传文件格式
    
    :param: filedName 服务器上传文件时取的字段名
    :param: dataList 上传的图片数组的二进制表示
    :param: parameters 上传的参数
    
    :returns: 拼接后的二进制格式
    */
//    private class func formData(filedName:String,dataList:[String:NSData!],parameters:[String:AnyObject]? = nil) ->NSData? {
//        var dataM = NSMutableData()
//        // 1.遍历字典,拼接字符串参数
//        if let params = parameters {
//            for (k,v) in params {
//                var strM = "--\(boundary)\r\n"
//                strM += "Content-Disposition: form-data; name=\"\(k)\"\r\n"
//                strM += "\(v)\r\n"
//                dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
//            }
//        }
//        // 2.遍历文件数据类型
//        for (k,v) in dataList {
//            var strM = "--\(boundary)\r\n"
//            strM += "Content-Disposition:form-data; name=\"\(filedName)\";filename=\"\(k)\"\r\n"
//            strM += "Content-Type:application/octet-stream \r\n\r\n"
//            dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
//            dataM.appendData(v)
//            dataM.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
//        }
//        
//        // 3.请求结束字符串
//        let tailing = "--\(boundary)--\r\n"
//        dataM.appendData(tailing.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
//        
//        return dataM
//    }
    private class func formData(fieldName: String, dataList:[String: NSData!], parameters: [String: AnyObject]? = nil) -> NSData {
        
        var dataM = NSMutableData()
        
        // 1. 遍历字典，拼接字符串参数
        if let params = parameters {
            for (k, v) in params {
                var strM = "--\(boundary)\r\n"
                strM += "Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n"
                strM += "\(v)\r\n"
                
                dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            }
        }
        
        // 2. 遍历文件数据数组
        for (k, v) in dataList {
            var strM = "--\(boundary)\r\n"
            strM += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(k)\"\r\n"
            strM += "Content-Type: application/octet-stream\r\n\r\n"
            
            dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            // 追加文件数据
            dataM.appendData(v)
            dataM.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        }
        
        // 3. 请求结尾字符串，告诉服务器，上传数据已经结束
        let tail = "--\(boundary)--\r\n"
        dataM.appendData(tail.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        
        return dataM
    }

}
